﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//
using System.IO;
using iPublic;


namespace HRecycle.Comm
{
    /// <summary>
    /// 识别，海宏软件，周承昊
    /// 修改记录：
    ///   20171212，zch
    /// </summary>
    public partial class FrmShiBie : Form
    {
        public iCamera camera = null;               //摄像头控制
        public iPublic.API.ShiBie api = null;       //识别用
        public iPublic.API.WoMen womenAPI = null;   //自己的api
        public string sPaiZhaoFile = "";

        public FrmShiBie()
        {
            InitializeComponent();
        }

        private void FrmShiBie_Load(object sender, EventArgs e)
        {   //初始化
            try
            {
                showInfo("★★进入拍照识别单元★★");
                //
                if (!iDefine.debugMode) FormBorderStyle = FormBorderStyle.None;
                WindowState = FormWindowState.Maximized;
                cameraControl.Dock = DockStyle.Fill;
                tm_RunOnce.Enabled = true;
            }
            catch (Exception x)
            {
                showInfo(x.Message);
            }
        }
        private void tm_RunOnce_Tick(object sender, EventArgs e)
        {
            tm_RunOnce.Enabled = false;         //关闭自身，避免多次触发
            try
            {
                FormBorderStyle = FormBorderStyle.None;
                WindowState = FormWindowState.Maximized;
                cameraControl.Dock = DockStyle.Fill;
                //打开串口，开灯
                if (iDefine.comHelper.isPortReady) iDefine.comHelper.打开拍照led灯();

                //初始化摄像头对象
                camera = new iCamera(cameraControl) { showInfoProc = new iDefine.showInfoProc(showInfo) };
                camera.Start();
                //启动拍照、识别
                tm_work.Tag = gsClass.varToIntDef(lbl_time.Text, Convert.ToInt16(tm_work.Tag));
                tm_work.Enabled = true;
            }
            catch (Exception x)
            {
                showInfo("FormLoad错误：" + x.Message);
            }
        }

        private void tm_work_Tick(object sender, EventArgs e)
        {   //执行拍照并识别
            Timer tm = tm_work;
            bool lEnable = tm.Enabled;
            tm.Enabled = false;                 //关闭自身
            int nTime = gsClass.varToIntDef(lbl_time.Text, 3) - 1;
            try
            {
                lbl_time.Text = nTime.ToString();
                if (nTime == 0)
                {
                    runWork(lEnable);
                    return;
                }
                else
                {
                    tm.Enabled = lEnable;
                }
            }
            catch (Exception x)
            { showInfo(x.Message); }
        }

        public iDefine.ChuLiJieGuo runWork(bool lTimerEnable)
        {   //执行拍照识别
            iDefine.ChuLiJieGuo result = new iDefine.ChuLiJieGuo(), jg = null;
            Timer tm = tm_work;
            Bitmap bitmap = null;
            iDefine.jsonShibieOK shibieOK = null;
            iDefine.json验证物品 yanzheng = null;
            DialogResult khSelect = DialogResult.None;
            bool lEnable = lTimerEnable;
            string s = iDefine.findSysFile("App.Config"), sFile = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            string sMat = "";
            try
            {
                //拍照
                if (File.Exists(s)) sFile = Path.GetDirectoryName(s);
                sFile += "\\" + "Temp\\";
                if (!Directory.Exists(sFile)) Directory.CreateDirectory(sFile);
                sFile += "ShiBie" + "" + ".jpg";  //png格式的，DateTime.Now.ToString("yyyyMMdd_hhmmss");
                camera.PaiZhao(ref bitmap, sFile);

                //阿里识别
                showInfo("正在识别：" + sFile);
                if (api == null) api = new iPublic.API.ShiBie() { showInfoProc = new iDefine.showInfoProc(showInfo) };
                jg = api.shiBie(sFile);
                if (jg.error != 0 || jg.data == null) throw new Exception("识别错误：" + jg.error.ToString() + "," + jg.message);
                if ((shibieOK = jg.data as iDefine.jsonShibieOK) != null)
                    sMat = shibieOK.result[0].id + "/" + shibieOK.result[0].description + "/" + shibieOK.result[0].description_en;
                showInfo("FACE识别完毕" + jg.error.ToString() + "：" + sMat);

                //发到自己服务器上识别是不是要这个东西
                if (womenAPI == null) womenAPI = new iPublic.API.WoMen();
                jg = womenAPI.验证物品(shibieOK, sFile);
                if (jg.error != 0) throw new Exception("错误：识别出错，或者您投放的物品我们暂不接收");
                yanzheng = jg.data as iDefine.json验证物品;
                if (string.IsNullOrEmpty(yanzheng.msg)) yanzheng.msg = ""; else yanzheng.msg += ".";
                yanzheng.msg += sMat;

                //识别成功之后的处理
                khSelect = callOK(shibieOK);
                if (khSelect == DialogResult.Cancel)
                {   //客户要求取回
                    iDefine.comHelper.电机右转取回口();
                    iDefine.comHelper.打开出物口led灯();
                    System.Threading.Thread.Sleep(100);
                }
                else
                {   //收起物品
                    iDefine.comHelper.电机左转储物箱();
                    iDefine.toufangList.Add(yanzheng);
                }
            }
            catch (Exception x)
            {
                showInfo(x.Message);
                iDefine.comHelper.电机右转取回口();
                iDefine.comHelper.打开出物口led灯();
                //tm.Enabled = lEnable;           //出错的，继续
                khSelect = callFaile(shibieOK, x.Message);
            }
            sPaiZhaoFile = sFile;                   //记下文件名
            //iDefine.comHelper.关闭出物口led灯();
            //判断处理
            if (khSelect == DialogResult.Retry || khSelect == DialogResult.Ignore)
            {   //继续投放
                lbl_time.Text = (Convert.ToInt16(tm.Tag) + 7).ToString();  //原始记录3秒，继续投放需要电机回转5秒，投放上也需要时间
                tm.Enabled = lEnable;
            }
            else
            {   //结束投放，返回到原来的窗口
                Close();
                DialogResult = khSelect;
            }
            return result;
        }

        public DialogResult callOK(iDefine.jsonShibieOK shibie)
        {   //识别成功后，然用户选择是：完成、继续投放、识别错了不投放了
            DialogResult result = DialogResult.OK;
            //FrmShiBieOK frm = null;
            //try
            //{
            //    frm = new Comm.FrmShiBieOK();
            //    frm.shibie = shibie;
            //    result = frm.ShowDialog();
            //}
            //catch (Exception x)
            //{
            //    showInfo(x.Message);
            //}
            //frm.Dispose();
            return result;
        }

        public DialogResult callFaile(iDefine.jsonShibieOK shibie, string errMessage)
        {   //识别有问题或者不要，让用户选择：继续投放、取消不投放了
            DialogResult result = DialogResult.Cancel;
            //FrmShiBieFaile frm = null;
            //try
            //{
            //    frm = new FrmShiBieFaile();
            //    frm.lbl_message.Text = errMessage;
            //    result = frm.ShowDialog();
            //}
            //catch (Exception x)
            //{
            //    showInfo(x.Message);
            //}
            //frm.Dispose();
            return result;
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void FrmShiBie_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                showInfo("正在释放资源");
                if (cameraControl.CameraCreated) cameraControl.CloseCamera();
                if (camera != null) camera.Dispose();
                camera = null;
                //关灯
                if (iDefine.comHelper.isPortReady) iDefine.comHelper.关闭所有led灯();
                //删掉文件
                if (File.Exists(sPaiZhaoFile)) File.Delete(sPaiZhaoFile);
            }
            catch (Exception x)
            {
                showInfo(x.Message);
            }
        }

        public void showInfo(string sInfo, bool lTime = true)
        {
            string s = sInfo;
            if (lTime) s = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " " + sInfo;
            lbl_info.Text = s;
            //写日志
            iLog.writeLogFile(sInfo);
        }

        
    }
}
